<template>
  <div class="w-full h-full">
    <div v-if="stageIndex === 0" class="type-intro text-333">
      <span class="type">听后记录并转述（共2节；每节5分，共10分）</span>
      <p class="mt-10px">
        <span class="intro"
          >听短文，记录关键信息并转述短文内容，本大题共两节。第一节，听两遍短文，根据所听内容和提示将所缺的关键信息填写在相应位置上，每空只需填写一个词。第二节，听第三遍短文，根据所听内容和提示进行转述</span
        >
      </p>
    </div>
    <Stem v-else :data="stem" />
    <Recorder ref="recorderRef" @error="handlerRecorderError" />
  </div>
</template>

<script>
import Stem from '@/components/question/stem/index'
import { mapState } from 'vuex'
import { generateStudentAnswer, formatQuestionStem } from '@/utils/question'
import Recorder from '@/components/recorder'
import { uploadFile } from '@/api/common'

export default {
  components: { Stem, Recorder },
  inject: ['_addTagClickHandler', '_removeTagClickHandler', 'globalData'],
  props: {},
  data() {
    return {}
  },
  computed: {
    stageIndex() {
      const { stageIndex } = this.globalData.controller

      return stageIndex
    },
    currentStage() {
      return this.globalData.controller.getCurrentStage()
    },
    ...mapState(['homework']),
    currentHomework() {
      return this.homework.currentHomework
    },
    currentQuestion() {
      const { questions, questionIndex } = this.currentHomework

      return questions[questionIndex]
    },
    stem() {
      const { questionStem } = this.currentStage

      if (!questionStem) return ''

      const {
        stem: {
          info: { question: questions }
        },
        localStudentAnswer: { studentAnswer }
      } = this.currentQuestion
      const [question_fill] = questions
      const studentAnswerFill = {
        anSqs: studentAnswer.anSqs[0]
      }
      const stem = JSON.parse(question_fill.stem)
      const {
        info: { std = [] }
      } = stem

      let templateStd = ''
      try {
        std.forEach((s, index) => {
          const { xth } = s
          let fillAnswer = '点此填空'
          try {
            const answer = studentAnswerFill.anSqs[index].ans[0].anStudent
            answer && (fillAnswer = answer)
          } catch (error) {}
          templateStd += `<p>${xth}.<span class="fill" data-index="${index}">${fillAnswer}</span></p>`
        })
      } catch (error) {}

      const copyQuestionStem = JSON.parse(JSON.stringify(questionStem))
      copyQuestionStem.html = copyQuestionStem.html.replace(
        '</p></div>',
        `</p>${templateStd}</div>`
      )
      return copyQuestionStem
    }
  },
  created() {
    this.$on('pause', () => {})
    this.$on('resume', () => {})
  },
  mounted() {
    this._addTagClickHandler('span', this.handleSpanClick)
  },
  beforeDestroy() {
    this._removeTagClickHandler('span', this.handleSpanClick)
  },
  methods: {
    init(stageIndex) {
      const {
        stem: {
          info: { question: questions }
        },
        localStudentAnswer: { studentAnswer }
      } = this.currentQuestion

      if (!Array.isArray(questions)) return

      const genStemFill = (question, studentAnswer) => {
        const stem = JSON.parse(question.stem)
        const {
          info: { image = '' }
        } = stem

        return formatQuestionStem({
          html: `<div><span style="font-size:0.22rem;font-weight:500">听后记录信息</span><p><span>现在你有1分钟的时间浏览提示信息。</span></p><p><img src="${image}" /></p></div>`,
          og: null,
          sqs: [],
          type: '英语听说-听后记录'
        })
      }

      const genStemPicture = (question, studentAnswer) => {
        const stem = JSON.parse(question.stem)
        const {
          info: { image = '', analyze = '' }
        } = stem

        return formatQuestionStem({
          html: `<div><span style="font-size:0.26rem;font-weight:500">听后转述信息</span><p><span>请再听一遍短文，完成转述。</span></p><p>${analyze}</><p><img src="${image}" /></p></div>`,
          og: null,
          sqs: [],
          type: '英语听说-听后转述'
        })
      }

      const [question_fill, question_picture] = questions
      const stem_fill = genStemFill(question_fill, {
        anSqs: studentAnswer.anSqs[0]
      })
      const stem_picture = genStemPicture(question_picture, {
        anSqs: studentAnswer.anSqs[1]
      })

      let stages = [
        {
          name: '题型说明',
          operateTips: '听短文，记录关键信息并转述短文内容，本大题共两节。',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_3_desc.mp3'
        }
      ]

      const {
        info: { audio: audio_fill = '' }
      } = JSON.parse(question_fill.stem)
      const {
        info: { audio: audio_picture = '' }
      } = JSON.parse(question_picture.stem)
      stages = stages.concat([
        {
          name: '播放题干',
          questionIndex: 0,
          questionStem: stem_fill,
          operateTips: '现在你有1分钟的时间浏览提示信息',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_3_1_1.mp3'
        },
        {
          name: '阅读题目',
          questionIndex: 0,
          questionStem: stem_fill,
          operateTips: '准备时间',
          duration: 60 * 1000
        },
        {
          name: '播放对话第一遍',
          questionIndex: 0,
          questionStem: stem_fill,
          operateTips: '第一遍',
          duration: audio_fill
        },
        {
          name: '播放对话第二遍',
          questionIndex: 0,
          questionStem: stem_fill,
          operateTips: '第二遍',
          duration: audio_fill
        },
        {
          name: '填空输入',
          questionIndex: 0,
          questionStem: stem_fill,
          operateTips: '下面，请在90秒钟内将所缺信息填入到指定区域',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_3_1_2.mp3',
          ignoreCountdown: true
        },
        {
          name: '开始填空输入',
          questionIndex: 0,
          questionStem: stem_fill,
          operateTips: '请填空输入',
          duration: 90 * 1000,
          ignoreSpeed: true
        },
        {
          name: '播放题干',
          questionIndex: 1,
          questionStem: stem_picture,
          operateTips: '请再听一遍短文，完成转述',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_3_2_1.mp3'
        },
        {
          name: '播放对话',
          questionIndex: 1,
          questionStem: stem_picture,
          operateTips: '播放中',
          duration: audio_picture
        },
        {
          name: '转述准备',
          questionIndex: 1,
          questionStem: stem_picture,
          operateTips: '下面，你有2分钟的时间做转述准备。转述的开头已给出',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_3_2_2.mp3'
        },
        {
          name: '空120秒',
          questionIndex: 1,
          questionStem: stem_picture,
          operateTips: '请阅题',
          duration: 120 * 1000,
          ignoreSpeed: true
        },
        {
          name: '准备录音',
          questionIndex: 1,
          questionStem: stem_picture,
          operateTips: '下面，请准备录音。听到提示音后，在2分钟内完成转述',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_3_2_3.mp3'
        },
        {
          beforeRunAction: () => {
            this.$refs.recorderRef.stop()
          },
          name: '开始录音',
          questionIndex: 1,
          questionStem: stem_picture,
          operateTips: '提示音',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/Di.mp3'
        },
        {
          beforeRunAction: () => {
            this.$refs.recorderRef.start()
          },
          name: '录音',
          questionIndex: 1,
          questionStem: stem_picture,
          operateTips: '录音中',
          duration: 120 * 1000,
          ignoreSpeed: true
        },
        {
          name: '停止录音',
          questionIndex: 1,
          questionStem: stem_picture,
          operateTips: '停止录音',
          duration: () => {
            return new Promise((resolve) => {
              const loading = this.$loading({
                lock: true,
                text: '保存录音...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.5)'
              })
              // 一分钟内上传不成功关闭loading弹窗
              const timer = setTimeout(() => {
                loading.close()
              }, 60000)
              const {
                stem: {
                  info: { question: questions }
                },
                localStudentAnswer
              } = this.currentQuestion
              const [question_fill, question_picture] = questions
              const { questionId } = question_picture
              const { examId, studentId } = localStudentAnswer

              this.$refs.recorderRef.stop(async (res) => {
                const { data, file, format } = res

                const date = Date.now()
                const uploadPath = `exam/${examId}/${studentId}/${questionId}/0/0/${date}.${format}`
                const formData = new FormData()
                formData.append('file', file, `${date}.${format}`)
                formData.append('path', uploadPath)

                try {
                  const { data: answer } = await uploadFile(formData)
                  const studentAnswerItem = localStudentAnswer.studentAnswer.anSqs[1]
                  studentAnswerItem[0].ans[0] = {
                    anStudentUrl: answer
                  }
                  this.$set(localStudentAnswer.studentAnswer.anSqs, 1, studentAnswerItem)
                  this.currentQuestion.localStudentAnswerStatus = 1
                  resolve()
                } catch (error) {
                  console.error(error)
                } finally {
                  clearTimeout(timer)
                  loading.close()
                }
              })
            })
          }
        }
      ])

      this.globalData.controller.reset()
      this.globalData.controller.init(stages, stageIndex)
    },
    handleSpanClick(node) {
      if (node.className.indexOf('fill') != -1) {
        const { index } = node.dataset
        const { localStudentAnswer } = this.currentQuestion

        this.$prompt('请输入答案', '提示', {
          inputValue: node.innerHTML && node.innerHTML != '点此填空' ? node.innerHTML : '',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(({ value }) => {
            try {
              const studentAnswerItem = localStudentAnswer.studentAnswer.anSqs[0]
              studentAnswerItem[index].ans[0].anStudent = value
              this.$set(localStudentAnswer.studentAnswer.anSqs, 0, studentAnswerItem)
              this.currentQuestion.localStudentAnswerStatus = 1
              node.innerHTML = value ? value : '点此填空'
            } catch (error) {}
          })
          .catch(() => {})
      }
    },
    handlerRecorderError({ message }) {
      this.$message.error(message)
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .fill {
  display: inline-block;
  width: auto;
  height: 34px;
  background-color: #51c3ff;
  font-size: 18px;
  line-height: 34px;
  color: #fff;
  border-radius: 6px;
  margin-left: 4px;
  padding: 0 12px;
}
</style>
